<template>
  <div class="container">
    <div class="app-container">
      <div class="left">
        <el-input
          ref="searchRef"
          v-model="params.keyword"
          style="margin-bottom:10px"
          type="text"
          prefix-icon="el-icon-search"
          size="small"
          placeholder="输入员工姓名全员搜索"
          @change="onSearch"
        />
        <!-- 树形组件 -->
        <el-tree
          ref="treeRef"
          :data="depts"
          :props="defaultProps"
          default-expand-all
          :expand-on-click-node="false"
          highlight-current
          node-key="id"
          @current-change="selectNode"
        />
      </div>
      <div class="right">
        <el-row class="opeate-tools" type="flex" justify="end">
          <el-button v-permission="'add-employee'" size="mini" type="primary" @click="$router.push('/employee/detail')">添加员工</el-button>
          <el-button size="mini" @click="openExcelDialog">excel导入</el-button>
          <el-button size="mini" @click="exportEmployee">excel导出</el-button>
        </el-row>
        <!-- 表格组件 -->
        <el-table :data="employeeList">
          <el-table-column prop="staffPhoto" label="头像" align="center">
            <template v-slot="{ row }">
              <el-avatar v-if="row.staffPhoto" :size="30" :src="row.staffPhoto" style="margin-top: 5px;" />
              <span v-else class="username">{{ row.username.charAt(0) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="username" label="姓名" />
          <el-table-column prop="mobile" label="手机号" sortable />
          <el-table-column prop="workNumber" label="工号" sortable />
          <el-table-column prop="formOfEmployment" label="聘用形式">
            <template v-slot="{ row }">
              <span>{{ row.formOfEmployment === 1 ? '正式' : row.formOfEmployment === 0 ? '非正式' : '无' }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="departmentName" label="部门" />
          <el-table-column prop="timeOfEntry" label="入职时间" />
          <el-table-column prop="" label="操作" width="280px">
            <template v-slot="{ row }">
              <el-button type="text" size="mini" @click="$router.push(`/employee/detail/${row.id}`)">查看</el-button>
              <el-button type="text" size="mini" @click="openRoleDialog(row.id)">角色</el-button>
              <el-popconfirm
                title="确认删除改行数据吗？"
                @onConfirm="delEmployee(row.id)"
              >
                <el-button slot="reference" type="text" size="mini" style="margin-left: 10px;">删除</el-button>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-row type="flex" justify="end" style="height: 60px" align="middle">
          <el-col :span="12">
            <el-pagination
              layout="total, prev, pager, next"
              :current-page="params.page"
              :page-size="params.pagesize"
              :total="total"
              @current-change="changePage"
            />
          </el-col>
        </el-row>
      </div>
    </div>
    <!-- excel导入弹层 -->
    <import-excel :show-excel-dialog.sync="showExcelDialog" @onUploadSuccess="getEmployeeList" />
    <!-- 角色弹层 -->
    <el-dialog :visible.sync="showRoleDialog" title="分配角色">
      <el-checkbox-group v-model="roleIds">
        <el-checkbox v-for="item in roleList" :key="item.id" :label="item.id">{{ item.name }}</el-checkbox>
      </el-checkbox-group>
      <el-row slot="footer" type="flex" justify="center">
        <el-col :span="6">
          <el-button size="mini" type="primary" @click="onRoleSubmit">确定</el-button>
          <el-button size="mini" @click="showRoleDialog = false">取消</el-button>
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
import { deptGetDepartmentsApi } from '@/api/department'
import { emAssignRolesApi, emDelEmployeeApi, emExportEmployeeAPi, emGetEmployeeDetailApi, emGetEmployeeListApi, emGetRoleListApi } from '@/api/employee'
import { transListToTreeData } from '@/utils'
import FileSaver from 'file-saver'
import ImportExcel from './components/import-excel.vue'

export default {
  name: 'Employee',
  components: {
    ImportExcel
  },
  data() {
    return {
      depts: [], // 部门列表
      defaultProps: {
        label: 'name',
        children: 'children'
      },
      params: {
        page: 1,
        pagesize: 5,
        keyword: '',
        departmentId: null
      },
      employeeList: [], // 员工列表
      total: null,
      showExcelDialog: false, // 控制excel导入弹层显隐
      showRoleDialog: false, // 控制角色权限弹层显隐
      roleList: [], // 角色列表
      roleIds: [], // 角色列表选中的 ids
      roleId: null
    }
  },
  created() {
    this.getDepartments()
    this.getRoleList()
  },
  methods: {
    /**
     * 获取树形数据
     */
    async getDepartments() {
      this.depts = transListToTreeData(await deptGetDepartmentsApi(), 0)
      // 记录默认选中节点
      this.params.departmentId = this.depts[0].id
      // 树形组件渲染是异步的，等到组件渲染完后，再获取组件实例对象
      this.$nextTick(() => {
        // 设置选中节点
        this.$refs.treeRef.setCurrentKey(this.depts[0].id)
      })
      // 首次获取员工列表
      this.getEmployeeList()
    },
    /**
     * 获取员工列表
     */
    async getEmployeeList() {
      const { rows, total } = await emGetEmployeeListApi(this.params)
      this.employeeList = rows
      this.total = total
    },
    /**
     * 选中节点
     * @param node 当前节点的数据
     */
    selectNode(node) {
      this.params.departmentId = node.id
      this.params.page = 1
      this.getEmployeeList()
    },
    /**
     * 页码切换
     * @param newPage 切换后的页码
     */
    changePage(newPage) {
      this.params.page = newPage
      this.getEmployeeList()
    },
    /**
     * 条件搜索
     */
    onSearch() {
      this.params.page = 1
      this.getEmployeeList()
      this.$refs.searchRef.blur()
    },
    /**
     * excel导出点击事件
     */
    async exportEmployee() {
      const res = await emExportEmployeeAPi()
      FileSaver.saveAs(res, '员工信息表.xlsx')
      this.$message.success('导出成功~')
    },
    /**
     * excle导入点击事件
     */
    openExcelDialog() {
      this.showExcelDialog = true
    },
    /**
     * 删除员工
     * @param id 员工 id
     */
    async delEmployee(id) {
      await emDelEmployeeApi(id)
      this.$message.success('删除员工成功~')

      if (this.employeeList.length === 1 && this.params.page > 1) this.params.page--

      this.getEmployeeList()
    },
    /**
     * 获取角色列表
     */
    async getRoleList() {
      this.roleList = await emGetRoleListApi()
    },
    /**
     * 打开角色弹层
     * @param id 员工 id
     */
    async openRoleDialog(id) {
      const { roleIds } = await emGetEmployeeDetailApi(id)
      this.roleIds = roleIds
      this.roleId = id
      this.showRoleDialog = true
    },
    /**
     * 分配员工角色
     */
    async onRoleSubmit() {
      await emAssignRolesApi({ id: this.roleId, roleIds: this.roleIds })
      this.$message.success('分配角色成功~')
      this.showRoleDialog = false
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  background: #fff;
  display: flex;
  .left {
    width: 280px;
    padding: 20px;
    border-right: 1px solid #eaeef4;
  }
  .right {
    flex: 1;
    padding: 20px;
    .opeate-tools {
      margin:10px ;
    }
    .username {
      height: 30px;
      width: 30px;
      line-height: 30px;
      text-align: center;
      border-radius: 50%;
      color: #fff;
      background: #04C9BE;
      font-size: 12px;
      display:inline-block;
    }
  }
}
</style>
